import { uploadFileUsingPost } from '@/services/backend/fileController';
import { LoadingOutlined, PlusOutlined} from '@ant-design/icons';
import {message, Upload, type UploadProps} from 'antd';
import React from 'react';
import {COS_HOST} from "@/constants";

interface Props {
  biz: string;
  onChange?: (url:string) => void;
  value?: string;
}

const PictureUploader: React.FC<Props> = (props) => {
  const { biz, value, onChange } = props;
  const [loading, setLoading] = React.useState(false);
  const uploadProps: UploadProps = {
    name: 'file',
    listType:'picture-card',
    multiple: false,
    maxCount: 1,
    showUploadList:false,
    disabled: loading,
    customRequest: async (fileObj: any) => {
      setLoading(true);
      try {
        const res = await uploadFileUsingPost(
          {
            biz,
          },
          {},
          fileObj.file,
        );
        fileObj.onSuccess(res.data);
        const fullPath=COS_HOST+res.data;
        onChange?.(fullPath??'');
        message.success('上传成功');
      } catch (e) {
        message.error('上传失败');
        fileObj.onError(e);
      }
      setLoading(false);
    },
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  return (
    <>
      <Upload {...uploadProps}>
        {value ? <img src={value} alt={"picture"} style={{width:'100%'}}/> : uploadButton}
      </Upload>
    </>
  );
};
export default PictureUploader;
